from datetime import datetime
import time
import os
import shutil
import stat
from pathlib import Path
import sys

from configDev import sync_frequency,  to_sync_files_list, to_sync_again, to_thorough_copy, to_sync_dirs_list, FROM_WORKSPACE_ROOT, TO_WORKSPACE_ROOT
# files and dirs to sync
from decorator import setInterval

is_reverse = False


def judge_to_swap(left, right):
    if is_reverse:
        return right, left
    else:
        return left, right


def sync_dirs():
    for directory in to_sync_dirs_list:
        from_path = Path(FROM_WORKSPACE_ROOT + '\\' + directory)
        to_path = Path(TO_WORKSPACE_ROOT + '\\' + directory)
        from_path, to_path = judge_to_swap(from_path, to_path)

        if not (from_path.exists()):
            print('不存在目录:', directory)
            continue

        if to_thorough_copy and to_path.exists():
            # os.system('rimraf "{}"'.format(to_path))  # 需要时间
            # time.sleep(1)  # 保证任务完成,
            shutil.rmtree(to_path)
            time.sleep(0.1)  # 保证任务完成,
            shutil.copytree(from_path, to_path, dirs_exist_ok=True)
        else:
            shutil.copytree(from_path, to_path, dirs_exist_ok=True)


def sync_files():
    for file_name in to_sync_files_list:
        file_from = Path(FROM_WORKSPACE_ROOT + '\\' + file_name)
        file_to = Path(TO_WORKSPACE_ROOT + '\\' + file_name)
        file_from, file_to = judge_to_swap(file_from, file_to)
        if not os.path.exists(file_from):
            print('不存在:' + file_from.name)
            continue
        if not os.path.exists(file_to):
            file_to.parents[0].mkdir(parents=True, exist_ok=True)
        shutil.copy(file_from, file_to)


times = 0


def show_times():
    global times
    times += 1
    print('synced ' + times.__str__() + ' times')


@setInterval(sec=sync_frequency)
def sync_again():
    pass


def entry():
    sync_files()
    sync_dirs()
    show_times()
    if to_sync_again:
        sync_again()


# read input from terminal: https://blog.csdn.net/PPLLO_o/article/details/99057765

if __name__ == '__main__':
    print('sync start')
    if sys.argv[1:] and sys.argv[1:][0] == 'r':
        is_reverse = True
        print('从招商端到用户端')
    else:
        print('从用户端到招商端')
    entry()

    current_time = datetime.now().strftime("%H:%M:%S")
    print('sync end: ' + current_time)
